<template>
    <!-- 商品管理 -->
    <div class="scheme">
        <div class="header-box">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="商品状态：">
                    <el-select v-model="formInline.status" placeholder="请选择" clearable>
                        <el-option label="全部" value=""></el-option>
                        <el-option label="上架" value="1"></el-option>
                        <el-option label="下架" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品名称搜索：">
                    <el-input v-model="formInline.name" placeholder="请输入搜索商品名称"></el-input>
                </el-form-item>
                <el-form-item label="商品ID搜索：">
                    <el-input v-model="formInline.id" placeholder="请输入搜索商品ID"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="submitForm">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" icon="el-icon-plus" @click="addCourse">新增</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="tables">
            <el-table border :data="tableData" max-height="650" highlight-current-row :row-style="{height: '20px'}"
                      :header-cell-style="{background:'#e6e6e6',color:'#000000'}">
                <el-table-column prop="id" align="center" label="ID" width="60"></el-table-column>
                <el-table-column prop="name" align="center" label="名称"></el-table-column>
                <el-table-column prop="original_price" align="center" label="原价"></el-table-column>
                <el-table-column prop="price" align="center" label="售价"></el-table-column>
<!--                <el-table-column prop="stock_num" align="center" label="库存"></el-table-column>-->
<!--                <el-table-column prop="lock_num" align="center" label="锁定库存"></el-table-column>-->
                <el-table-column prop="can_point_pay" align="center" label="可用积分支付" width="80">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.can_point_pay === 1 ? 'success' : 'danger'" disable-transitions>
                            {{ scope.row.can_point_pay === 1 ? '是' : '否' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="sale_num" align="center" label="已售"></el-table-column>
                <el-table-column prop="tag_names" label="商品标签" align='center' width="160">
                    <template slot-scope="scope">
                        <el-tag :type="'success'" v-for="item in scope.row.tag_names" :key="item">
                            {{ item }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="status" align="center" label="商品状态" width="80">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'"
                                disable-transitions>{{ scope.row.status === 1 ? '上架' : '下架' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="order" align="center" label="序号"></el-table-column>
                <el-table-column prop="created_at" align="center" label="创建时间"></el-table-column>

                <el-table-column align="center" label="操作" width="300">
                    <template slot-scope="scope">
                        <el-button size="mini" type="success" plain icon="el-icon-edit" @click="handleEdit(scope.row)">
                            编辑
                        </el-button>

                        <el-button size="mini" type="danger" plain icon="el-icon-delete"
                                   @click="handleDelete(scope.row)">删除
                        </el-button>
<!--                        <el-button size="mini" type="warning" plain @click="handleAddStock(scope.row)">-->
<!--                            新增库存-->
<!--                        </el-button>-->
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                               :current-page.sync="page" :page-sizes="[15, 20, 50, 100]" :page-size="limit"
                               layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>
        </div>

        <!-- 新增弹框 -->
        <el-dialog :title="title" :visible.sync="dialogAddGoods" width="60%">
            <el-form :model="form" label-width="100px" :rules="rules">
                <el-form-item label="商品名称:" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="标签:" prop="tag_id">
                    <el-checkbox-group v-model="form.tag_id">
                        <el-checkbox v-for="item in tagList" :key="item.code" :label="item.code">
                            {{ item.name }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="原价:" prop="original_price">
                    <el-input v-model="form.original_price" placeholder="请输入售价" style="width: 20%;">
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="售价:" prop="price">
                    <el-input v-model="form.price" placeholder="请输入售价" style="width: 20%;">
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="可用积分支付:" prop="is_top">
                    <el-radio-group v-model="form.can_point_pay" size="medium">
                        <el-radio border label="1">是</el-radio>
                        <el-radio border label="2">否</el-radio>
                    </el-radio-group>
                </el-form-item>
<!--                <el-form-item label="库存:" prop="stock_num" v-if="!isEdit">-->
<!--                    <el-input v-model="form.stock_num" placeholder="请输入库存" style="width: 20%;"></el-input>-->
<!--                </el-form-item>-->
                <el-form-item label="排序">
                    <el-input-number v-model="form.order" :min="1" :max="10000"></el-input-number>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="form.status"
                               active-value="1"
                               inactive-value="2"
                    ></el-switch>
                </el-form-item>
                <el-form-item label="图片" prop="images">
                    <el-upload
                        list-type="picture-card"
                        accept="jpeg,jpg,png,PNG"
                        :action="uploadUrl"
                        :auto-upload="true"
                        :limit="imageLimit"
                        :multiple="imageMultiple"
                        :file-list="form.images"
                        :show-file-list="true"
                        :on-remove="handleImageRemove"
                        :on-preview="handleImagePreview"
                        :on-success="handleImageSuccess"
                        :before-upload="beforeImageUpload"
                        :on-exceed="handleImageExceed"
                        :on-error="imgUploadError"
                    >
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogImageVisible"><img width="100%" :src="dialogImageUrl" alt=""/>
                    </el-dialog>
                    <div><P style="color: #FF4D51;">注意：图片仅支持jpeg,jpg,png格式，请上传4张！</P></div>
                </el-form-item>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogAddGoods = false">取 消</el-button>
                <el-button type="primary" @click="submitGoodsData">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 新增库存弹框 -->
        <el-dialog title="新增库存" :visible.sync="dialogStock" width="60%" :show-close="false"
                   :close-on-click-modal="false" :close-on-press-escape="false">

            <el-form :model="stockForm" label-width="100px" :rules="stockRules">
                <el-form-item label="商品名称:" prop="num">
                    {{ this.stockForm.name }}
                </el-form-item>
                <el-form-item label="已有库存:" prop="num">
                    {{ this.stockForm.stock_num }}
                </el-form-item>
                <el-form-item label="新增库存数:" prop="num">
                    <el-input v-model="stockForm.num" style="width: 200px"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogStock = false">取 消</el-button>
                <el-button type="primary" @click="submitStockData">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>

export default {
    name: "goods",
    data() {
        return {
            formInline: {
                status: "",
                name: "",
                id: "",
            },
            form: {
                name: "",
                tag_id: [],
                original_price: '',
                price: "",
                can_point_pay:"",
                stock_num: '',
                order: '',
                status: '',
                images: [],

            },
            tableData: [],
            id: 0,
            dialogAddGoods: false, //默认新增框隐藏
            title: "新增 ", //默认新增
            isEdit: false, //默认为新增
            page: 1, //默认第一页
            limit: 10, //默认一页显示10条数据
            total: 0,

            uploadUrl: '',
            isUpload: false,//是否图片上传
            dialogVisible: false,

            tagList: [{code: 1, name: "热门推荐"},{code: 2, name: "最新上架"}],
            //约课详情
            dialogInfo: false,
            pageInfo: 1, //默认第一页
            limitInfo: 15, //默认一页显示10条数据
            totalInfo: 0,
            userCourseList: [],
            course_id: 0,
            infoForm: {nickname: '', mobile: ''},
            rules: {
                name: [{required: true, message: "请输入商品名称", trigger: "blur"}],
                original_price: [{required: true, message: "请输入原价", trigger: "blur"}],
                price: [{required: true, message: "请输入售价", trigger: "blur"}],
                can_point_pay: [{required: true, message: "请选择标签", trigger: "blur"}],
                images: [{required: true, message: "请上传商品图片", trigger: "blur"}],
            },

            dialogImageVisible: false,
            dialogImageUrl: '',
            imageLimit: 4,
            imageMultiple: true,

            dialogStock: false,
            stockForm: {num: ''},
            stockRules: {num: [{required: true, message: "请输入商品名称", trigger: "blur"}]},
            goods_id: '',
        };
    },
    created() {
        this.formInline.id = this.$route.query.id;
        this.getGoodsList();
        this.uploadUrl = this.$api.imageUpload;
    },
    activated() {
        this.formInline.id = this.$route.query.id;
        this.getGoodsList();
        this.uploadUrl = this.$api.imageUpload;
    },
    components: {},
    methods: {
        // 点击新增课程按钮
        addCourse() {
            this.title = "新增商品";
            this.dialogAddGoods = true;
            this.isEdit = false;
            this.form.name = "";
            this.form.stock_num = "";
            this.form.sale_num = "";
            this.form.tag_id = [];
            this.form.original_price = "";
            this.form.price = "";
            this.form.images = [];
            this.form.order = "";
            this.form.status = "";

        },
        getGoodsList(page, limit) {
            let params = {
                page: this.page,
                per_page: this.limit,
                status: this.formInline.status,
                name: this.formInline.name,
                id: this.formInline.id,
            };
            this.$get(this.$api.goodsApi, params).then((res) => {
                if (res.code == 200) {
                    this.tableData = res.data.data;
                    this.total = res.data.total;
                } else {
                    return this.$message.error(res.msg);
                }
            });
        },
        forEachFun(str) {
            let ids = [];
            if (str.length > 0) {
                ids = str.split(",");
                ids.forEach((item, index) => {
                    ids[index] = parseInt(ids[index])

                });
            }
            return ids;

        },
        // 点击编辑按钮
        handleEdit(row) {
            this.title = "编辑";
            this.id = row.id;
            this.form.name = row.name;
            this.form.tag_id = this.forEachFun(row.tag_ids);
            this.form.price = row.price;
            this.form.can_point_pay = row.can_point_pay.toString();
            this.form.original_price = row.original_price;
            this.form.order = row.order;
            this.form.status = row.status.toString();
            this.form.images = row.images;
            this.dialogAddGoods = true;
            this.isEdit = true;
        },
        // 点击编辑弹框取消按钮
        goToEdit() {
            this.dialogAddGoods = false;
            this.isEdit = false;
        },

        // 点击删除按钮
        handleDelete(row) {
            this.$confirm("此操作将永久删除此条数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.$delete(this.$api.goodsApi + "/" + row.id).then((res) => {
                        if (res.code == 200) {
                            this.getGoodsList(this.page, this.limit);
                            return this.$message.success("删除成功！");
                        } else {
                            return this.$message.error(res.msg);
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },
        handleAddStock(row) {
            this.dialogStock = true;
            this.stockForm.num = '';
            this.stockForm.name = row.name;
            this.stockForm.stock_num = row.stock_num;
            this.goods_id = row.id;


        },
        // 分页
        handleSizeChange(size) {
            this.limit = size;
            this.getGoodsList();
        },
        handleCurrentChange(index) {
            this.page = index;
            this.getGoodsList();
        },
        // 点击查询按钮
        submitForm() {
            this.getGoodsList();
        },


        // 提交课程数据确定按钮
        submitGoodsData() {
            if (this.form.name == "") {
                return this.$message.error("请输入名称！");
            }
            if (this.form.tag_id.length ==0) {
                return this.$message.error("请选择标签！");
            }

            if (this.form.original_price == "") {
                return this.$message.error("请输入原价！");
            }
            if (this.form.price == "") {
                return this.$message.error("请输入售价！");
            }
            if (this.form.can_point_pay == "") {
                return this.$message.error("请选择是否可用积分支付！");
            }
            if (this.form.images == "") {
                return this.$message.error("请上传图片！");
            }
            // if (!this.isEdit) {
            //     if (this.form.stock_num == "") {
            //         return this.$message.error("请输入库存数！");
            //     }
            //
            // }

            let params = {
                name: this.form.name,
                tag_id: this.form.tag_id,
                original_price: this.form.original_price,
                price: this.form.price,
                can_point_pay: this.form.can_point_pay,
                order: this.form.order,
                status: this.form.status,
                images: this.form.images,
            };

            if (this.isEdit) {
                this.$put(this.$api.goodsApi + "/" + this.id, params).then((res) => {
                    if (res.code == 200) {
                        this.form.status = false;
                        this.dialogAddGoods = false;
                        this.getGoodsList(this.page, this.limit);
                        return this.$message.success("编辑成功！");
                    } else {
                        return this.$message.error(res.msg);
                    }
                });
            } else {
                // params.stock_num = this.form.stock_num;
                this.$post(this.$api.goodsApi, params).then((res) => {
                    if (res.code == 200) {
                        this.form.status = false;
                        this.dialogAddGoods = false;
                        this.getGoodsList(this.page, this.limit);
                        return this.$message.success("新增成功！");
                    } else {
                        return this.$message.error(res.msg);
                    }
                });
            }
        },
        submitStockData() {
            if (this.stockForm.num == '' || this.stockForm.num <= 0) {
                return this.$message.error('请输入正确新增库存数');
            }
            this.$post(this.$api.goodsStockNumApi, {num: this.stockForm.num,id:this.goods_id}).then((res) => {
                if (res.code == 200) {
                    this.dialogStock = false;
                    this.getGoodsList(this.page, this.limit);
                    return this.$message.success("新增成功！");
                } else {
                    return this.$message.error(res.msg);
                }
            });


        },
        handleImageRemove(file, fileList) {

            //移除图片
            this.form.images = fileList;
        },
        // 点击查看预览图片
        handleImagePreview(file) {
            //预览图片时调用
            this.dialogImageUrl = file.url;
            this.dialogImageVisible = true;
        },
        handleImageSuccess(res, file) {
            this.form.image = URL.createObjectURL(file.raw);
            if (res.code == 200) {
                this.form.images.push({url: res.data.url});
                this.isUpload = true
            }

        },
        beforeImageUpload(file) {
            const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/gif');
            console.log('file.type', file.type)
            const isLt10M = file.size / 1024 / 1024 < 10;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 jpeg、png或者gif格式!');
            }
            if (!isLt10M) {
                this.$message.error('上传头像图片大小不能超过 10MB!');
            }
            return isJPG && isLt10M;
        },
        //图片上传超过数量限制提示
        handleImageExceed(file, fileList) {
            this.$message.error('上传图片数量超过上限');
        },
        //图片上传失败调用
        imgUploadError(err, file, fileList) {
            this.$message.error('上传图片失败!');
        },
    },
};
</script>

<style scoped>
.pagination {
    text-align: center;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.is-selected {
    color: #1989fa;
}
</style>
